<script setup lang="ts">
import type { StudentHomeworkView } from '@/types'
import { useAsyncState, useDebounceFn } from '@vueuse/core'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import message from '@/components/common/message'
import { PageTable } from '@/components/common/pagetable'
import Select from '@/components/common/Select.vue'
import TextInput from '@/components/common/TextInput.vue'
import LatestHomework from '@/components/homepage/LatestHomework.vue'
import { Search, Star } from '@/components/icons'
import { getHomeworkCompletionList } from '@/request/teacher/homework'

const name = ['状态', '学号', '姓名', '作业提交时间', '得分', '能力评价', '操作']

// 获取路由参数
const route = useRoute()
const classId = route.params.classId as string
const homeworkId = route.params.id as string

// 搜索和筛选参数
const searchKeywords = ref('')
const forceRefresh = ref(0)
const statusType = ref('')

// 学生作业数据
const studentData = ref<StudentHomeworkView[]>([])

const { state: homeworkDetail, isLoading } = useAsyncState(
  () => getHomeworkCompletionList({
    classId,
    homeworkId,
    pageNum: 1,
    pageSize: 4,
  }).then(res => ({
    id: homeworkId,
    className: res.entry.clazz,
    title: res.entry.homeworkTitle,
    publishTime: res.entry.publishTime,
    deadline: res.entry.ddl,
    status: res.entry.status === 0 ? '进行中' : '已截止',
    totalStudents: res.entry.allCount,
    completedStudents: res.entry.completionCount,
    uncompletedStudents: res.entry.uncompletedCount,
    students: res.entry.records.map(student => ({
      studentId: student.studentNo || '',
      studentName: student.studentName || '',
      submitTime: student.submitTime || '',
      score: student.score || 0,
      status: student.status === 1 ? '已完成' : '未完成',
      star: student.abilityLevel || 0,
    })),
  })).then((res) => {
    studentData.value = res.students
    return res
  }),
  {
    id: homeworkId,
    className: '',
    title: '',
    publishTime: '',
    deadline: '',
    status: '',
    totalStudents: 0,
    completedStudents: 0,
    uncompletedStudents: 0,
    students: [],
  },
)

// 学生作业完成情况数据获取函数
async function fetcher(page: number, pageSize: number) {
  try {
    // 调用API获取学生作业完成情况
    const data = await getHomeworkCompletionList({
      classId,
      homeworkId,
      status: statusType.value ? (statusType.value === '已完成' ? '1' : '0') : null,
      studentName: searchKeywords.value || null,
      pageNum: page,
      pageSize,
    })

    // 转换数据格式
    studentData.value = data.entry.records.map(student => ({
      studentId: student.studentNo || '',
      studentName: student.studentName || '',
      submitTime: student.submitTime || '',
      score: student.score || 0,
      status: student.status === 1 ? '已完成' : '未完成',
      star: student.abilityLevel || 0,
    }))

    return {
      total: data.entry.total,
      page,
      pageSize,
    }
  }
  catch (error) {
    console.error('获取学生作业完成情况失败:', error)
    message.error('获取学生作业完成情况失败')
    return {
      total: 0,
      page,
      pageSize,
    }
  }
}

// 渲染星级难度
function renderStars(ind: number, difficulty: number) {
  if (ind > difficulty) {
    return '#e4e4e4'
  }
  if (difficulty < 3) {
    return 'var(--primary-color-300)'
  }
  return 'var(--primary-color)'
}

// 防抖处理搜索
const handleFilterUpdate = useDebounceFn(() => forceRefresh.value++, 600)

// 筛选条件变化时重新获取数据
function handleSelectUpdate() {
  forceRefresh.value++
}
</script>

<template>
  <div class="min-width-wrapper">
    <div class="content-header">
      作业完成详情
    </div>
    <LatestHomework
      v-if="!isLoading"
      :homework="{
        id: homeworkDetail.id,
        className: homeworkDetail.className,
        title: homeworkDetail.title,
        publishTime: homeworkDetail.publishTime,
        ddl: homeworkDetail.deadline,
        status: homeworkDetail.status,
        totalStudents: homeworkDetail.totalStudents,
        completedStudents: homeworkDetail.completedStudents,
        uncompletedStudents: homeworkDetail.uncompletedStudents,
        classId,
      }" icon
    />
    <div class="card-area filter-options">
      <Select
        v-model:model-value="statusType" label="状态:" placeholder="全部状态"
        :options="[
          {
            label: '全部状态',
            value: '',
          }, {
            label: '已完成',
            value: '已完成',
          }, {
            label: '未完成',
            value: '未完成',
          }]" @update:model-value="handleSelectUpdate"
      />
      <TextInput v-model="searchKeywords" label="姓名:" placeholder="请输入学生姓名" @update:model-value="handleFilterUpdate">
        <template #suffix>
          <Search />
        </template>
      </TextInput>
      <div />
    </div>
    <div class="filter-result">
      <PageTable v-model:force-refresh="forceRefresh" :fetcher="fetcher" :default-page-size="4">
        <template #header>
          <div class="header">
            <div v-for="i in name" :key="i" class="header-item">
              {{ i }}
            </div>
          </div>
        </template>
        <template #default>
          <div v-for="(student,) in studentData" :key="student.studentId" class="data-row">
            <div class="data-item status-tag">
              <span class="tag" :class="student.status === '已完成' ? 'active-tag' : 'stopped-tag'">
                {{ student.status }}
              </span>
            </div>
            <div class="data-item">
              {{ student.studentId }}
            </div>
            <div class="data-item">
              {{ student.studentName }}
            </div>
            <div class="data-item">
              {{ student.status === '已完成' ? student.submitTime : '暂无' }}
            </div>
            <div class="data-item">
              {{ student.score || '暂无' }}
            </div>
            <div class="data-item">
              <Star v-for="i in 5" :key="i" :stroke="renderStars(i, student.star)" />
            </div>
            <div class="data-item actions">
              <span v-if="student.status === '已完成'" class="action-btn edit-btn">查看详情</span>
              <span v-else class="action-btn delete-btn">暂无</span>
            </div>
          </div>
        </template>
      </PageTable>
    </div>
  </div>
</template>

<style scoped>
.content-header {
  margin-bottom: 2rem;
}

.min-width-wrapper {
  min-width: 860px;
}

.card-area.filter-options {
  padding: 18px 12px;
  margin-top: 12px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 25px;
}

.filter-result {
  margin-top: 21px;
  margin-bottom: 58px;
  --grid-style: 80px 300px 100px 150px 80px 2fr minmax(90px, 1fr);

  .header {
    display: grid;
    grid-template-columns: var(--grid-style);

    .header-item {
      text-align: center;
      padding: 10px 8px;
    }
  }

  .data-row {
    display: grid;
    grid-template-columns: var(--grid-style);
    border-bottom: 1px solid #eaeaea;
    min-height: 50px;
    align-items: center;

    .data-item {
      padding: 10px 8px;
      display: flex;
      justify-content: center;
      align-items: center;

      &.status-tag {
        .tag {
          width: 3.3rem;
          height: 20px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 1000px;
          font-size: 10px;
          color: white;
          font-weight: 500;
        }

        .active-tag {
          background: #284af9;
        }

        .stopped-tag {
          background-color: #db0000;
        }
      }

      &.title {
        font-size: 14px;
        color: #333;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        position: relative;

        &::after {
          content: '';
          background-color: #333;
          width: 20%;
          height: 100%;
          position: absolute;
          right: 0;
          background: linear-gradient(to right, #ffffff00, #ffffff);
        }
      }

      &.class {
        font-size: 14px;
        color: #333;
      }

      &.time {
        font-size: 13px;
        color: #666;
      }

      &.completion {
        .progress-container {
          margin-top: 4px;
          width: 100%;
          display: flex;
          align-items: flex-start;
          flex-direction: column;
          gap: 4px;

          .progress-bar {
            width: 90%;
            height: 11px;
            background-color: #e5e7eb;
            border-radius: 30px;
            overflow: hidden;

            .progress-fill {
              height: 100%;
              border-radius: 30px;
              background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-color-300) 100%);
              transition: width 0.3s ease;
            }
          }

          .progress-text {
            font-size: 10px;
            color: #6e6e6e;
            text-align: center;
          }
        }
      }

      &.actions {
        display: flex;
        gap: 15px;

        .action-btn {
          font-size: 14px;
          transition: all 0.2s;

          &.edit-btn {
            cursor: pointer;
            color: var(--primary-color);
          }

          &.delete-btn {
            color: var(--text-color);
          }
        }
      }
    }

    &:hover {
      background-color: #fafafa;
    }
  }
}
</style>
